#!/usr/bin/perl -W
#------------------------------------------------------------------------
#                      UC TECH IP Copyright 
#------------------------------------------------------------------------
#FileName: UtilextraModuleTree.pl
#Function: 
#	Extra sub module recusively for given module file, and print 
#	the path of sub module into given include file 
#Parameter:
#	$1:Source Path
#	$2:Target Path
#	$3:Given Module file
#	$4:Include file
#	$5~$$:Exclude Module 


my $SourcePath = shift @ARGV;
my $TargetPath = shift @ARGV;
my $TopModule = shift @ARGV;
my $IncludeFile = shift @ARGV;

my @ExcludeModule = @ARGV;
`rm $IncludeFile`;
open INCLUDE,">>$IncludeFile";

sub CheckExcludeModule{
	my $GivenModule = shift @_;
	foreach(@ExcludeModule){
		if($_ eq $GivenModule){
			return 1;
		}
	}
	return 0;
}
sub ExtraSubModule{
	my @SubModuleQueue;
	my $Module = shift @_;
	my $ModuleFile = "$SourcePath/$Module";
	if(-e $ModuleFile)
	{
		if($SourcePath ne $TargetPath)
		{
			`cp $ModuleFile $TargetPath/$Module`;
		}
		print INCLUDE "\`include \"$TargetPath/$Module\"\n";
		open FILE,"< $ModuleFile";
		while(<FILE>) {
			if((/^\s*(\w+)\s*\w+\s*\(\s*$/) || (/^\s*(\w+)\s*\#\s*\(/))
			{
				if($1 ne "module"){
					my $CheckResult = &CheckExcludeModule($1);
					if($CheckResult != 1) {
						unshift(@SubModuleQueue,$1);		
					}
				}
			}
		}
		foreach(@SubModuleQueue){
			my $Meta = $_;
			&ExtraSubModule("$Meta.v"); 
		}
		close FILE;
	}
}


&ExtraSubModule ($TopModule);
close INCLUDE;
`sort $IncludeFile | uniq > temp.v`;
`rm $IncludeFile`;
`mv temp.v $IncludeFile`;
